'''
A set of rules that verifies the proper use of selenium commands  
'''

from string import Template
from rsa.report import ReportManager
from rsa.rule import TemplateRule, RuleViolation
from rsa.util.common_utilities import is_variable

name = "Selenium"

description = __doc__

report = ReportManager()

class BasicSeleniumCommand(TemplateRule):
    """
    This rule find instances where basic Selenium commands are badly used (Input Text, Select, Check, etc).
    """
    
    rule_id = "BasicSeleniumCommand"
    name = "Basic selenium command"
    message = Template("Argument $item1 can't be a list in '$item2' keyword")
    solution = Template("Remove argument $item1")
    example = '''
            # invalid function call
            Input Text | cp_text2 | @{propertyIDS}   
    '''
    severity = 0
    description = "BasicSeleniumCommand find instances where basic Selenium commands are badly used (Input Text, Select, Check, etc)."
    commands = ["Input Text", "Select", "Check"]
       
    def visit_step(self, step):
        if(step.keyword in self.commands):
            for arg in step.args:
                if(arg.find("@{") != -1):
                    begin = arg.find("[")
                    end = arg.find("]")
                    if(begin > -1 and end > -1 and end > begin):
                        value = arg[begin + 1: end]
                        if(not(value.isnumeric() or is_variable(value))):
                            args = [arg, step.keyword]
                            report.add_rule_violation(RuleViolation(self, step, args, self.node, self.line))
                    else:
                        args = [arg, step.keyword]
                        report.add_rule_violation(RuleViolation(self, step, args, self.node, self.line))
                    
    def visit_loop(self, loop):
        for step in loop.steps:
            self.line += 1
            self.visit(step)
